package com.lbjhan.rpc.handler;

import com.lbjhan.rpc.common.RpcRequest;
import com.lbjhan.rpc.common.RpcResponse;
import com.lbjhan.rpc.pojo.SerializerOption;
import com.lbjhan.rpc.serializer.ISerializer;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ReplayingDecoder;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class RpcCommonDeCoder extends ReplayingDecoder {

    private static Map<Integer, Class<?>> classOptionMap;
    static {
        classOptionMap = new HashMap();
        classOptionMap.put(0, RpcRequest.class);
        classOptionMap.put(1, RpcResponse.class);
    }

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        int serializerOption = byteBuf.readInt();
        Class<?> aClass = Class.forName(SerializerOption.getClassName(serializerOption));
        ISerializer serializer = (ISerializer) aClass.newInstance();
        int classOption = byteBuf.readInt();
        int length = byteBuf.readInt();
        byte[] bytes =  new byte[length];
        byteBuf.readBytes(bytes);
        Object obj = serializer.deserialize(bytes, classOptionMap.get(classOption));
        list.add(obj);
    }
}
